package org.gongliang.jsmile.common.kit.file;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.gongliang.jsmile.common.kit.StrKit;
import org.gongliang.jsmile.config.oss.OSSFactory;
import org.gongliang.jsmile.config.oss.OSSService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.common.collect.Lists;

/**
 * 文件上传工具类
 * 
 * @author 龚亮
 * @version 1.0
 */
public class FileKit {

	private static final Logger logger = LoggerFactory.getLogger(FileKit.class);

	/**
	 * 单文件上传
	 * 
	 * @param prefix
	 *            上传目录前缀
	 */
	public static UploadFile upload(HttpServletRequest request, String prefix) {
		List<UploadFile> files = multiUpload(request, prefix);
		if (files != null && files.size() > 0) {
			return files.get(0);
		}
		return null;
	}

	/**
	 * 多文件上传
	 * 
	 * @param prefix
	 *            上传目录前缀
	 */
	public static List<UploadFile> multiUpload(HttpServletRequest request, String prefix) {
		List<UploadFile> files = Lists.newArrayList();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) (request);
			Iterator<String> iter = multiRequest.getFileNames();
			OSSService oss = OSSFactory.build();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String myFileName = file.getOriginalFilename();
					if (StrKit.isNotEmpty(myFileName.trim())) {
						UploadFile uploadFile = new UploadFile(file, prefix);
						String url = oss.upload(uploadFile.getIn(), uploadFile.getPath());
						logger.debug("上传文件：" + uploadFile.getOriginalFilename() + "成功,返回url:" + url);
						uploadFile.setUrl(url);
						files.add(uploadFile);
					}
				}
			}
		}
		return files;
	}
}
